﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using global::HtmlAgilityPack;

namespace ZapHelper
{
    public class Category
    {
        #region Properties
        
        #region Category Name

        public String Name { get; set; }
        
        #endregion
        
        #region Products Url

        public Uri ProductsUri { get; set; }
        
        #endregion
       
        #region Products

        public IEnumerable<Product> Products
        {
            get
            {
                return getProducts();
            }
        }

        #endregion
     
        #region Document

        private HtmlDocument m_document { get; set; }

        public HtmlDocument Document
        {
            get
            {
                if (m_document == null)
                {
                    // For thread safety
                    lock (this)
                    {
                        if (m_document == null)
                        {
                            // Create a new XmlDocument  
                            m_document = Utils.DownloadWebPage(ProductsUri);
                        }
                    }
                }
                return m_document;
            }
        }

        #endregion

        #endregion

        #region Methods
        
        private IEnumerable<Product> getProducts()
        {
            var document = Document;

            // Select All of the <a> nodes.
            var products =
                document.DocumentNode.SelectNodes("//product");

            if (products != null)
            {
                foreach (var productNode in products)
                {
                    Product product;
                    try
                    {
                        product = new Product(productNode);
                    }
                    catch
                    {
                        // Ignored purposely 
                        continue;
                    }

                    yield return product;
                }
            }

        }
        
        private String getNodeValue()
        {
            return String.Empty;

        }


        #endregion

    }
}
